package com.多线程.ThreadPool;

import java.util.concurrent.*;

/**
 * 目标：自定义一个线程池对象，处理Runnable任务，并测试其特性
 */

public class TreadPoolDemo1 {
    public static void main(String[] args) {
        //1.创建一个线程池对象
        /**
         int corePoolSize,
         int maximumPoolSize,
         long keepAliveTime,
         TimeUnit unit,
         BlockingQueue<Runnable> workQueue,
         ThreadFactory threadFactory,
         RejectedExecutionHandler handler
         */
        ExecutorService pool=new ThreadPoolExecutor(3,5,6, TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(5),new ThreadPoolExecutor.AbortPolicy());


        //2.创建Runnable任务交给线程池处理(任务只要创建一个就好了，这里表示的是让线程池处理多个任务)
        MyRunnable myRunnable = new MyRunnable();
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        pool.execute(myRunnable);
        //线程池执行完任务以后是不会关闭的，实际开发中也不会去关闭线程池
        //任务数量少于8个是不会创建临时线程的

        //数量大于8个就会创建临时线程
        pool.execute(myRunnable);
        //此时就看到有临时线程在执行任务
        //pool-1-thread-1输出0
        //pool-1-thread-1输出1
        //pool-1-thread-4输出0
        //pool-1-thread-4输出1
        //pool-1-thread-4输出2
        //pool-1-thread-1输出2
        //pool-1-thread-1输出3

        //当任务数量大于10的时候任务会被拒绝（这里我们使用的是抛出异常的方法）
//        pool.execute(myRunnable);
//        pool.execute(myRunnable);
        //Running, pool size = 5, active threads = 5, queued tasks = 5, completed tasks = 0  提示已经完成的线程数量是0

        //关闭线程池
        pool.shutdownNow();//立即关闭，任务没完成也关闭
//        pool.shutdown();//等任务执行完以后在关闭

    }
}
